define(["../common"], function() {
	
	var $cartList = $(".cart-list");
	
	$.getJSON(g_userDomain + "/shoppingCart/list/json", function(data) {
		if (data.status !== 0) {
			$(".nr").html(data.message);
			return;
		}
		var cartList = data.result;
		if (!cartList || cartList.length == 0) {
			$(".nr").html("查无记录");
			return;
		}
		$(".nr").hide();
		$cartList.show();
		
		// 显示
		$cartList.parseHtml({
			data: cartList,
			beforeNode: {
				"shoppings": function(shopping) {
					if (!shopping.storeGoods.sellUnit) {
						shopping.storeGoods.sellUnit = shopping.storeGoods.unit;
					}
				}
			}
		});
		$(window).scroll();
		
		// 绑定事件
		for (var i in cartList) {
			for (var j in cartList[i].shoppings) {
				initShopping(cartList[i].shoppings[j]);
			}
		}
		
		// 
		stat();
	});
	
	// 选店铺
	$(document).on('click', "[id^=cartId_]", function() {
		$(this).trigger('check');
		
		var $this = $(this);
		var cartId = $this.id(1);
		var $shoppingChs = $("#shoppings_" + cartId).find(".checkbox"); // shopping checkbox(s)
		// 控制商品选中状态
		if ($this.is(".check")) {
			$shoppingChs.trigger("checked");
		} else {
			$shoppingChs.trigger("uncheck");
		}
		stat();
		return false;
	});
	
	// 选商品
	$(document).on('click', "[id^=shoppings_] .checkbox", function() {
		$(this).trigger('check');
		
		var $shoppings = $(this).parents("[id^=shoppings_]");
		var cartId = $shoppings.id(1);
		var $cartCb = $("#cartId_" + cartId);// cart checkbox
		// 控制店铺选中状态
		if ($shoppings.find(".checkbox:not(.check)").length > 0) {
			$cartCb.trigger('uncheck');
		} else {
			$cartCb.trigger('checked');
		}
		stat();
		return false;
	});
	
	// 去结算
	$("#settleBt").click(function() {
		if ($("[id^='shoppings_'] .check").length == 0) {
			$(this).failMsg("请选择要结算的商品");
			return;
		}
		
		// 通过命名各表单项控制要提交的内容
		var cartIndex = -1, $this, cartId, $cart;
		$(".checkbox :checkbox").removeAttr("name");
		$("[id^=shopping_] .checkbox.check").each(function(i, el) {
			$this = $(this);
			cartId = $this.parents("[id^=shoppings_]").id(1);
			$cart = $("#cartId_" + cartId);
			
			if (!$cart.attr("name")) {
				cartIndex++;
				$cart.find(":checkbox").attr("name", "shoppingCarts[" + cartIndex + "].cartId");
				$cart.find(":checkbox").prop("checked", true);
			}
			$this.find(":checkbox").attr("name", "shoppingCarts[" + cartIndex + "].shoppingIds");
			
		});
		$("#form_cart").submit();
	});
	

	/**
	 * 给某个商品注册购买量更改事件
	 * @param shopping 商品物品信息
	 */
	function initShopping(shopping) {
		// 需要在html上增加以下参数:
		// 商品容器 #shopping_{shoppingId}
		// 加按钮 .bCountBt-a
		// 减按钮 .bCountBt-m
		// 数量文本框 .bCount
		// 删除按钮 .delBt
		
		var sp = shopping;// shopping
		var sg = sp.storeGoods;
		var $sp = $("#shopping_" + sp.shoppingId);
		var $buyCount = $sp.find(".bCount");
		
		// 缓存数据
		$sp.data("shopping", shopping);
		
		// 加减事件
		var bCountBtEvent_ = function(event) {
			var $bCountBt = $(event.currentTarget);
			var preCount = parseFloat($buyCount.val());
			if (isNaN(preCount)) {
				$buyCount.failMsg("请填写数字！");
				return;
			}
			$buyCount.val(preCount);
			
			// 加
			var destCount = preCount + sg.sellExt;
			// 减
			if ($bCountBt.is(".bCountBt-m")) {
				destCount = preCount - sg.sellExt;
				if (destCount < sg.sellMin) {
					destCount = sg.sellMin;
				}
			}
			
			if(destCount.toString().indexOf(".") > 0){
				// 小数计算保留一位小数
				$buyCount.val(destCount.toFixed(1));
			} else {
				$buyCount.val(destCount);
			}
			
			$buyCount.trigger("change");
		};
		// 编辑事件
		var bCountChangeEvent_ = function(event) {
			var buyCount = parseFloat($buyCount.val());
			if (isNaN(buyCount)) {
				$buyCount.failMsg("请填写数字！");
				return;
			}
			$buyCount.val(buyCount);
			
			// 已购买数
			var hbCount = sp.buyCount;
			// 剩余数
			var remain = sg.stockConvert - hbCount;
			if (remain <= 0) {
				buyCount = 0;
				$buyCount.val(0);
				$buyCount.failMsg("已无可购买库存！");
			} else if (buyCount <= 0) {
				buyCount = 0;
				$buyCount.failMsg("购买量不能为0");
			} else if (hbCount >  -1 && remain <  buyCount) {
				buyCount = remain;
				$buyCount.val(remain);
				var msg = "库存不足！最多还可购买：" + remain + sg.sellUnit;
				$buyCount.failMsg(msg);
			}
			
			$buyCount.loadMsg("请稍候...");
			$.post(g_userDomain + "/shopping/updateDo/json", {shoppingId: sp.shoppingId, buyCount: buyCount}, function(data) {
				if (data.status !== 0) {
					$buyCount.failMsg(data.message);
					return;
				} 
				$buyCount.hideMsg();
				stat();
			});
			
		};
		var bCountBlurEvent_ = bCountChangeEvent_;
		// 删除事件
		var delBtEvent_ = function(event) {
			var $this = $(this);
			if (!$this.lock()) return;
			
			$this.loadMsg("正在删除...");
			$.post(g_userDomain + "/shopping/delDo/json", {shoppingId: sp.shoppingId}, function(data) {
				if (data.status !== 0) {
					$this.failMsg(data.message);
					return;
				}
				$this.infoMsg("删除成功");
				$("#shopping_" + sp.shoppingId).remove();
				// 刷新购物车物品数量缓存值
				//shoppingCount(true);
				stat();
				
			});
		}
		
		// 事件:加/减购买量
		$sp.on('click', ".bCountBt-a", bCountBtEvent_);
		$sp.on("click", ".bCountBt-m", bCountBtEvent_);
		// 事件:输入
		$sp.on('blur', ".bCount", bCountBlurEvent_);
		// 事件:购买量变化
		$sp.on('change', ".bCount", bCountChangeEvent_);
		// 事件:删除
		$sp.on('click', ".delBt", delBtEvent_);
		
		
	}
	
	/**
	 * 金额统计
	 */
	function stat() {
		
		var totalPrice = 0, $this, $sp, sp, sg, buyCount, subtotal;
		
		$("[id^=shopping_] .checkbox.check").each(function(i, el) {
			$this = $(this);
			// $shopping
			$sp = $this.parents("[id^=shopping_]");
			// cache shopping
			sp = $sp.data("shopping");
			// storeGoods
			sg = sp.storeGoods;
			
			buyCount = parseFloat($sp.find(".bCount").val());
			
			// 计费单位与购买单位不一样
			if (sg.sellUnit && sg.sellUnit != sg.unit) {
				buyCount = buyCount * sg.unitConvert;
			}
			
			// 小计
			//subtotal = buyCount * sg.price;
			
			totalPrice += buyCount * sg.price;
			
		});
		
		$("#totalPrice").html("￥" + totalPrice.toFixed(1) + "0");
	}
});